/*
� 最佳准确率窗口:
{
  windowSize: 21,
  total: 1244,
  correct: 849,
  accuracy: 68.25,
  maxWrongStreak: 6
}

� 最小连续错误窗口:
{
  windowSize: 4,
  total: 1244,
  correct: 811,
  accuracy: 65.19,
  maxWrongStreak: 5
}

*/
// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule("../../../awakened-potential/helpers/readAllValues.js");
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) => (i + 1).toString().padStart(2, "0"));

/**
 * 根据窗口内遗漏次数最少策略选出 32 个号码
 */
const select32ByLeastOmission = (temp) => {
  const omissionCount = {};

  // 初始化
  allNumbers.forEach((n) => (omissionCount[n] = 0));

  // 统计每个号码在窗口内的“未中次数”
  temp.forEach((draw) => {
    const drawn = draw.number;
    allNumbers.forEach((n) => {
      if (n !== drawn) omissionCount[n] += 1;
    });
  });

  // 得分少的优先（越活跃）
  const sorted = Object.entries(omissionCount)
    .sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))
    .map(([num]) => num)
    .slice(0, 32);

  if (sorted.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${sorted.length} 个）`);
  }

  return sorted;
};

// ✅ 多窗口评估
const testResults = [];

for (let windowSize = 2; windowSize <= 200; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = allValues.slice(Math.max(0, index - windowSize), index);
    if (temp.length === 0) return;

    const selectedNumbers = select32ByLeastOmission(temp);
    if (selectedNumbers.length !== 32) {
      throw new Error("选出的32个号码数量不正确");
    }

    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct++;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak++;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }

    predictResults.push(selectedNumbers);
  });

  const total = predictResults.length;
  const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : "0.00";

  testResults.push({
    windowSize,
    total,
    correct,
    accuracy: Number(accuracy),
    maxWrongStreak,
  });
}

// ✅ 输出每个窗口的结果
testResults.forEach((res) => {
  console.log(
    `windowSize = ${res.windowSize}, 准确率 = ${res.accuracy}%, 最大连续错误次数 = ${res.maxWrongStreak}`
  );
});

// ✅ 输出最佳结果
const bestAccuracy = _.maxBy(testResults, "accuracy");
const bestStability = _.minBy(testResults, "maxWrongStreak");

console.log("\n📊 最佳准确率窗口:");
console.log(bestAccuracy);

console.log("\n🧱 最小连续错误窗口:");
console.log(bestStability);
